package com.travelexp;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;

public class UpdaterService extends Service{
	private SharedPreferences prefProvider;
	private Updater updater;
	private Location lastLocation;
	private TravelData travelData;
	private Listener listener;
	
	// Location stuff
	private boolean isRunning = false;
	private LocationManager locationManager;
	private long interval;
	private long previousInterval = 0;
	public float distance = 15;
	public long multTime = 60000;
	
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public synchronized void onCreate() {
		super.onCreate();		
		listener = new Listener();
		prefProvider = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		locationManager  = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		updater = new Updater();
		travelData = new TravelData(this);
		// Request the location for the first time
		if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
		    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

		}
		if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
		    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
		}
	}

	@Override
	public synchronized void onDestroy() {
		// Stop Thread
		updater.interrupt();
		isRunning = false;
		updater = null;
		// Close the database
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		prefProvider = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		// Start the updater 
		updater.start();
		return super.onStartCommand(intent, flags, startId);
	}
	
	public boolean requestLocation()
	{
		// If the last location is null is because the first request has not been executed yet
		if(lastLocation == null)
		{
			return false;
		}
		else
		{
			// Remove the request updates
			removeUpdates();
			// Set a new one with the new time
			if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
				locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 
						interval * multTime, 0, listener);			
			}
			if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
						interval * multTime, 0, listener);	
			}
			return true;
		}
	}
	
	// Remove the updates requests
	public void removeUpdates()
	{
		locationManager.removeUpdates(listener);
	}
	
	// Get the user's location
	private void saveLocation()
	{
		if(lastLocation == null) return;
		// Let's save this
		travelData.insertLocation(lastLocation, false);
		// Refresh UI
		Intent intent = new Intent(LocalsList.UPDATE_LOCALS);
		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);		
	}

	// Thread to access the location
	class Updater extends Thread 
	{
		@Override
		public void run() 
		{
			Looper.prepare();
			
			while(updater!=null)
			{
				interval = Long.valueOf(prefProvider.getString("time_interval", "15"));
				isRunning = prefProvider.getBoolean("serviceEnable", true);
				
				// Stop running
				if(!isRunning)
				{
					removeUpdates();
					// set the previous time to zero, in order to reestablish the requests on restart
					previousInterval = 0;
				}
				
				
				// If the interval changed
				if(previousInterval != interval && isRunning)
				{
					if(requestLocation())
					{
						previousInterval = interval;
					}
				}
				try 
				{
					if(isRunning) saveLocation();
					Thread.sleep(interval*multTime);
				} catch (InterruptedException e) 
				{
					// Interrupted
					e.printStackTrace();
					isRunning = false; 
				}
			}
		}

		@Override
		public void interrupt() {
			super.interrupt();
		}
	}

	public class Listener implements LocationListener
	{
		public void onLocationChanged(Location location) {
			if(location != null) lastLocation = location;
		}

		public void onProviderDisabled(String provider) {
			// Ignore it for now
			if(true)
			{
			}
		}

		public void onProviderEnabled(String provider) {
			// Ignore this for now
			if(true)
			{
			}
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// Ignore this for now
			if(true)
			{
			}		
		}	
	}
}
